import React, {
    Component,
} from 'react';
import LinearGradient from 'react-native-linear-gradient';
import {
    StyleSheet,
    Text,
    View,
    Platform,
    Dimensions,
    TouchableOpacity,
    Image,
    StatusBar,
    NativeModules,
    ScrollView,
    Switch, DeviceEventEmitter, ActivityIndicator,
    ToastAndroid,
    Clipboard,
    Alert,
    FlatList,
    TextInput
} from 'react-native';

import moment from 'moment';
import HttpUtils from '../../utils/HttpUtils';
import HttpUrls from '../../utils/HttpUrls';
import AndroidModule from "../../utils/AndroidConnent";
import { ToastToUser } from "../../utils/CustomToast";
import Constant from '../../utils/Constant'
import NoData from '../../utils/NoData'
import StatusBarSelf from '../../components/StatusBarSelf';

const isIos = Platform.OS == 'ios';
const screenW = Dimensions.get('window').width;
let navigation


let pageSize = 20
let pageNo = 1;
let itemNo = 0;

export default class FoursQueryHistory extends Component {
    constructor(props) {
        super(props);
        this.state = {
            keyword: '',
            dataArray: [],
            isRefresh: false,
            showFoot: 0, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
        }
    }

    componentDidMount() {
        this.getFoursQueryHistory(true)
    }

    render() {
        navigation = this.props.navigation;
        return (
            <View style={styles.container}>
                <StatusBarSelf />
                <View style={styles.toplayout}>
                    <TouchableOpacity
                        style={styles.fanhuibox}
                        activeOpacity={0.8}
                        onPress={this.finish}>
                        <Image source={require('source/image/comm/back.png')} style={styles.fanhui} />
                    </TouchableOpacity>

                    <View style={styles.inputBox}>
                        <Image source={require('source/image/comm/icon_sc_search.png')} style={styles.searchIcon} />
                        <TextInput
                            clearButtonMode='while-editing'
                            style={styles.textInput}
                            placeholder='请输入关键词'
                            returnKeyType='search'
                            value={this.state.aliAccount}
                            onEndEditing={() => {
                                this.getFoursQueryHistory(true)
                            }}
                            onChangeText={this.onChangeTextHandle}
                            onSubmitEditing={() => {
                                this.getFoursQueryHistory(true)
                            }}
                        />
                    </View>
                </View>

                {this.renderList()}

            </View>
        )
    }

    finish() {
        navigation.goBack();
    }

    onChangeTextHandle = (value) => {
        this.setState({
            keyword: value
        })
    }

    renderList() {
        return (
            <View style={{ flex: 1 }}>
                <FlatList
                    data={this.state.dataArray}
                    renderItem={this.renderItemView.bind(this)}
                    extraData={this.state}
                    ListHeaderComponent={this.renderHeader.bind(this)}
                    ListFooterComponent={this.renderFooter.bind(this)}
                    onEndReached={this._onEndReached.bind(this)}
                    onEndReachedThreshold={0.2}
                    onRefresh={this.refreshData}
                    refreshing={this.state.isRefresh}
                    ListEmptyComponent={this.renderEmpty.bind(this)}
                />
            </View>
        )
    }

    renderItemView({ item, index }) {
        return (
            <TouchableOpacity
                key={index}
                style={styles.itemContain}
                onPress={() => {
                    if (item.value.queryStatus == 1) {
                        // let obj = {
                        //     url: Constant.webDomain + '/insurance?' + (item.value.reportType == 1 ? 'fid=' : 'cid=') + item.value.id,
                        //     param: {
                        //         carName: item.value.carName ? item.value.carName : '--',
                        //         brandLogo: item.value.brandLogo ? item.value.brandLogo : '--',
                        //         vcode: item.value.vcode ? item.value.vcode : '--',
                        //         reportType: item.value.reportType+''
                        //     }
                        // }

                        let url = Constant.webDomain + '/insurance?' + (item.value.reportType == 1 ? 'fid=' : 'cid=') + item.value.id
                        console.log('url = ',url)
                        navigation.navigate('WebView', {source: url})
                    }
                }}
                activeOpacity={item.value.queryStatus == 1 ? 0.6:1.0}
            >
                <Image style={styles.brandIcon} defaultSource={require('source/image/comm/sc_default.png')} source={{ uri: item.value.brandLogo }} />
                <View style={{ marginLeft: 15, flexDirection: 'column', justifyContent: 'center', flex: 1 }}>
                    <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
                        {
                            item.value.queryStatus >= 0 ?
                                <View style={[styles.statusBox, { backgroundColor: item.value.queryStatus == 0 ? '#E4E4E4' : item.value.queryStatus == 1 ? '#53D96A' : '#FB3D3C' }]}>
                                    <Text style={[styles.statusText, { color: item.value.queryStatus == 0 ? '#666666' : '#FFFFFF' }]}>{item.value.queryStatus == 0 ? '查询中' : item.value.queryStatus == 1 ? '已出单' : '已退款'}</Text>
                                </View>
                                :
                                null
                        }

                        <Text style={styles.brandText}>{item.value.carName}</Text>
                        <Text style={styles.typeText}>{item.value.reportType == 1 ? '维保报告' : (item.value.reportType == 2 ? '出险记录' : '')}</Text>
                    </View>
                    <View style={{ marginTop: 14, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
                        <Text style={styles.vinText}>{'VIN：' + item.value.vcode}</Text>
                        <Text style={styles.typeText}>{moment(item.value.createTime).format("YYYY-MM-DD")}</Text>
                    </View>
                </View>
                {
                    this.state.dataArray.length - 1 > index ?
                        <View style={styles.itemSepLine} />
                        :
                        null
                }
            </TouchableOpacity>
        )
    }

    renderEmpty() {
        if (!this.state.isRefresh) {
            return (
                <NoData Desc="暂无数据" style={{ marginTop: gREM(200) }} />
            )
        } else {
            return (
                null
            )
        }
    }

    renderHeader() {
        return (
            <View style={styles.header}>
            </View>
        );
    }

    renderFooter() {
        if (this.state.showFoot === 1) {
            return <View style={{ height: Constant.bottomHeight }} />;
        } else if (this.state.showFoot === 2) {
            return (
                <View style={styles.footer}>
                    <ActivityIndicator size="small" color="#999999" />
                    <Text style={styles.loadMoreTextStyle}>正在加载更多数据...</Text>
                </View>
            );
        } else if (this.state.showFoot === 0) {
            return null;
        }
    }

    refreshData = () => {
        this.getFoursQueryHistory(true);
    }

    _onEndReached() {
        if (this.state.dataArray.length == 0) {
            return;
        }
        //如果是正在加载中或没有更多数据了，则返回
        if (this.state.showFoot != 0) {
            return null;
        }

        //底部显示正在加载更多数据
        this.setState({ showFoot: 2 });

        this.getFoursQueryHistory(false);
    }

    getFoursQueryHistory(refresh) {
        if (refresh) {
            pageNo = 1;
            itemNo = 0;
            this.setState({ isRefresh: true })
        } else {
            pageNo++;
        }

        let param = {
            pageNo: pageNo,
            pageSize: pageSize,
            merchantId: Constant.userInfo.merchantId,
        }
        if (this.state.keyword) {
            param['vcode'] = this.state.keyword
        }
        HttpUtils.postRequest(HttpUrls.maintenanceRecords, param)
            .then((result) => {
                if (refresh) {
                    this.setState({ dataArray: [] })
                }
                let data = result.data
                if (data) {
                    let resultList = data.resultList
                    let dataBlob = [];
                    let i = itemNo;
                    if (resultList && resultList != null && resultList.length > 0) {
                        resultList.map(function (item) {
                            dataBlob.push({
                                key: i,
                                value: item,
                            })
                            i++;
                        });
                        itemNo = i;
                        this.setState({
                            dataArray: this.state.dataArray.concat(dataBlob),
                            isRefresh: false,
                            showFoot: 1,
                        });
                        setTimeout(() => {
                            this.setState({
                                showFoot: dataBlob.length >= pageSize ? 0 : 1,
                            })
                            resultList = null;
                            dataBlob = null;
                        }, 200);
                    } else {
                        this.setState({
                            showFoot: 1,
                            isRefresh: false,
                        });
                    }
                } else {
                    this.setState({
                        showFoot: 1,
                        isRefresh: false,
                    });
                }
            })
            .catch((error) => {

            });
    }

}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F9F9F9',
    },
    toplayout: {
        width: screenW,
        height: isIos ? 44:49,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: '#ffffff'
    },
    fanhuibox: {
        position: 'absolute',
        width: 80,
        height: '100%',
        left: 0,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'flex-start',
    },
    fanhui: {
        width: 18,
        height: 16,
        marginLeft: 15,
    },
    inputBox: {
        position: 'absolute',
        left: 50,
        right: 15,
        height: 32,
        backgroundColor: '#F9F9F9',
        borderRadius: 4,
        paddingHorizontal: 10,
        flexDirection: 'row',
        alignItems: 'center'
    },
    searchIcon: {
        width: 14,
        height: 14,
    },
    textInput: {
        marginLeft: 10,
        color: '#333333',
        fontSize: 13,
        height: '100%',
        flex: 1,
        padding: 0
    },


    itemContain: {
        paddingHorizontal: 10,
        width: '100%',
        height: 90,
        backgroundColor: '#fff',
        flexDirection: 'row',
        justifyContent: 'flex-start',
        alignItems: 'center'
    },
    brandIcon: {
        width: 60,
        height: 60,
        borderRadius: 2,
    },
    brandText: {
        lineHeight: 21,
        flex: 1,
        marginLeft: 4,
        color: '#222222',
        fontSize: 15,
        fontWeight: '500'
    },
    statusBox: {
        width: 30,
        height: 14,
        justifyContent: 'center',
        alignItems: 'center',
        borderTopLeftRadius: 4,
        borderBottomRightRadius: 4,
    },
    statusText: {
        fontSize: 8,
        fontWeight: '500'
    },
    typeText: {
        color: '#999999',
        fontSize: 12,
    },
    vinText: {
        color: '#696969',
        fontSize: 14,
    },

    itemSepLine: {
        position: 'absolute',
        bottom: 0,
        left: 10,
        width: '100%',
        height: 0.5,
        backgroundColor: '#E4E4E4'
    },

    header: {
        width: '100%',
        height: 10,
    },

    footer: {
        flexDirection: 'row',
        height: 40,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#f6f6f6'
    },
    loadMoreTextStyle: {
        fontSize: 14,
        color: '#999999',
        marginStart: 10,
    },
})